import React from 'react';
import { SearchOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import {Column } from '@ant-design/charts';
import { each, groupBy } from '@antv/util';
import { AMapScene,PointLayer,LoadImage,LayerEvent} from '@antv/l7-react';
import img1 from './img/airport1.svg'
import img2 from './img/airport2.svg'
import {Drawer,Card,Table,Input,Button,  Space,Collapse } from "antd";
class FlightSystem extends React.Component {

    searchInput = React.createRef()
    timeout = null
    state={
        data:[], //全部数据
        flightData:[],//飞机数据
        apTop:[],//前十机场信息
        CityThroughputList:[], //各城市航班吞吐量
        visibleDrawer:false,
        visibleCard:false,
        loading:false,
        currentAptCname:'', //机场名字
        currentAirPort:{}, //机场数据
        currentFlightData:[], //当页显示的航班数据
        pagination:{  //分页器：当前页码、每页显示的条数、总条目数
            current: 1, //当前页码
            pageSize:10, //每页显示的条数
            total:0, //总条目数
        },
        search:{
            searchText:'',
            SearchedColumn:'',
        }
    };
    //点击机场图标
    handleClick = (e)=>{
        this.setState({
            loading: true,
            currentAirPort:e.feature,
            currentAptCname: e.feature.aptCname,
            visibleDrawer: true,
          },
          () => {
            const { currentAptCname, pagination } = this.state;
            const url = `http://flightapi.xiexianbo.xin/flight/getForg?fdstAptCname=${currentAptCname}&pageSize=${pagination.pageSize}`;
            fetch(url)
              .then((response) => response.json())
              .then((res) => {
                this.setState({
                  currentFlightData: res.data.data,
                  loading: false,
                  pagination: {
                    ...this.state.pagination,
                    total: res.data.total,
                  },
                });
                // console.log(this.state.pagination);
              });
          }
        );
    };

    //hover机场图标,mousemove做防抖
    handleMouseMove=(e)=>{
        if(this.timeout){clearTimeout(this.timeout)}
        this.timeout=setTimeout(() => {
          this.setState({
              currentAirPort:e.feature,
              currentAptCname: e.feature.aptCname,
          })
        }, 500);
    };

    //分页器改变
    handleTableChange=(newPagination)=>{
        this.setState({
          pagination: {
            ...this.state.pagination,
            ...newPagination,
          },
        },()=>{
        const {currentAptCname,pagination}=this.state
        const url = `http://flightapi.xiexianbo.xin/flight/getForg?fdstAptCname=${currentAptCname}&pageSize=${pagination.pageSize}&pageNo=${pagination.current}`;
        fetch(url)
            .then(response => response.json())
            .then(res => {
                this.setState({
                    currentFlightData:res.data.data,
                })
            });
        });
    };

    //关闭Drawer
    onClose = () => {
        this.setState({
          visibleDrawer: false,
          searchText:''
        });
    };

      //加载机场数据
    componentDidMount(){
        const url = 'http://flightapi.xiexianbo.xin/airPort/listAll';
        fetch(url)
            .then(response => response.json())
            .then(res => {
                this.setState({
                    data:res.data.data
                })
            });
        const flighturl = 'http://flightapi.xiexianbo.xin/flight/getTopAT';
        fetch(flighturl)
            .then(response => response.json())
            .then(res => {
                // console.log('机型前十'+res.data.data);
                this.setState({
                    flightData:res.data.data
                })
            });
        const apturl = 'http://flightapi.xiexianbo.xin/airPort/getTopAP';
        fetch(apturl)
            .then(response => response.json())
            .then(res => {
                // console.log('机场前十'+res.data.data);
                this.setState({
                    apTop:res.data.data
                })
            });
        const getCityThroughputList = 'http://flightapi.xiexianbo.xin/flight/getCityThroughputList?order=1&pageSize=100';
        fetch(getCityThroughputList)
            .then(response => response.json())
            .then(res => {
                const CityThroughputList=[]
                each(res.data.data,(e)=>{
                  CityThroughputList.push({
                    cityName:e.cityName,
                    "吞吐量":e.enterNum,
                    type:"进港",
                    total:e.totol,
                  })
                  CityThroughputList.push({
                    cityName:e.cityName,
                    "吞吐量":e.exitNum,
                    type:"出港"
                  })
                })
                this.setState({
                    CityThroughputList:CityThroughputList
                })
            });
    };

    handleSearch = (selectedKeys, confirm, dataIndex) => {
      confirm();
      this.setState({
          searchText:selectedKeys[0],
          searchedColumn:dataIndex
      });
    };

    handleReset = (clearFilters) => {
      clearFilters();
      this.setState({searchText:''});
    };
    
    getColumnSearchProps = (dataIndex) => {
      const {search} = this.state
      return {
          filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
            <div
              style={{
                padding: 8,
              }}
            >
              <Input
                ref={this.searchInput}
                placeholder={`Search ${dataIndex}`}
                value={selectedKeys[0]}
                onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                onPressEnter={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
                style={{
                  marginBottom: 8,
                  display: 'block',
                }}
              />
              <Space>
                <Button
                  type="primary"
                  onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
                  icon={<SearchOutlined />}
                  size="small"
                  style={{
                    width: 90,
                  }}
                >
                  Search</Button>
                <Button
                  onClick={() => clearFilters && this.handleReset(clearFilters)}
                  size="small"
                  style={{
                    width: 90,
                  }}
                >
                  Reset
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => {
                    confirm({
                      closeDropdown: false,
                    });
                    this.setState({
                      searchText:selectedKeys[0],
                      searchedColumn:dataIndex
                  });
                  }}
                >
                  Filter
                </Button>
              </Space>
            </div>),
          filterIcon: (filtered) => (<SearchOutlined style={{color: filtered ? '#1890ff' : undefined}}/>),
          onFilter: (value, record) => record[dataIndex]? record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()): '',
          onFilterDropdownVisibleChange: (visible) => {if (visible) { setTimeout(() => this.searchInput.current?.select(), 100); }},
          render: (text) => search.searchedColumn === dataIndex ? (
              <Highlighter highlightStyle={{ backgroundColor: '#ffc069', padding: 0, }}
              searchWords={[search.searchText]}
              autoEscape
              textToHighlight={text ? text.toString() : ''} /> ) : ( text ),
        }};

    onChange = (key) => {
      //   console.log(key);
    };

    render(){
        const { Panel } = Collapse;
        const {data,apTop,flightData,CityThroughputList,currentAirPort,visibleDrawer,loading,currentAptCname,currentFlightData,pagination}=this.state
        const columns = [
            {
              title: '航空公司',
              dataIndex: 'airCName',
              sorter: (a, b) => a.airCName.length - b.airCName.length,
              sortDirections: ['descend', 'ascend'],
              key:'airCName',
              ...this.getColumnSearchProps('airCName'),
            },
            {
              title: '到达时间',
              dataIndex: 'scheduledArrtime',
              sorter: (a, b) => Date.parse(a.scheduledArrtime) - Date.parse(b.scheduledArrtime),
              sortDirections: ['descend', 'ascend'],
              key: 'scheduledArrtime',
              ...this.getColumnSearchProps('scheduledArrtime'),
        }];
        const aptColumnConfig = {
            data:data,
            xField: 'aptCcity',
            yField: 'flightNumber',
            width:300,
            height:300,
            xAxis: {
              label: {
                autoRotate: false,
              },
            },
            yAxis: {
                label: {
                  title: "飞机数",
                },
              },
            slider: {
              start: 0.1,
              end: 0.2,
            },
        };
        const annotations=[];
        each(groupBy(CityThroughputList,'cityName'), (values, k) => {
            annotations.push({
              type: 'text',
              position: [k, values[0].total],
              content: `${values[0].total}`,
              style: {
                textAlign: 'center',
                fontSize: 14,
                fill: 'rgba(0,0,0,0.85)',
              },
              offsetY: -10,
            });
        });
        const CityThroughputconfig = {
          data:CityThroughputList,
          isStack: true,
          xField: 'cityName',
          yField: "吞吐量",
          seriesField: 'type',
          label: {
            position: 'middle',
            layout: [
              // 柱形图数据标签位置自动调整
              {
                type: 'interval-adjust-position',
              }, // 数据标签防遮挡
              {
                type: 'interval-hide-overlap',
              }, // 数据标签文颜色自动调整
              {
                type: 'adjust-color',
              },
            ],
          },
          slider: {
            start: 0.08,
            end: 0.15,
          },
          // 使用 annotation （图形标注）来展示：总数的 label
          annotations,
        };
        const flightColumnConfig = {
          data:flightData,
          xField: 'atype',
          yField: 'flightAmount',
          width:300,
          height:300,
          xAxis: {
            label: {
              autoRotate: false,
            },
          },
          yAxis: {
              label: {
                title: "飞机数",
              },
            },
        };
        const aptTopColumnConfig = {
          data:apTop,
          xField: 'aptCname',
          yField: 'flightNumber',
          width:300,
          height:300,
          xAxis: {
            label: {
              autoRotate: false,
            },
          },
          yAxis: {
              label: {
                title: "飞机数",
              },
            },
        };
        return (
            <>
                <AMapScene
                    option={{}}
                    map={{
                        center: [113.956, 32.569202],
                        pitch: 0,
                        style: 'light',
                        zoom: 3.2,
                    }} style={{
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        right: 0,
                        bottom: 0,}}>
                    <LoadImage  name="00" url= {img1}/>
                    <LoadImage  name="11" url= {img2}/>
                    <PointLayer
                        key={'2'}
                        aotoFit={true}
                        source={{data:data,parser:{type:"json",x:'longitude',y:'latitude'}}}
                        shape={{
                            field:'flightNumber',
                            values: (flightNumber)=>{
                                if(flightNumber > 1000){
                                    return '11'
                                }else{
                                    return '00'
                                }
                            },
                        }}
                        style={{opacity: 1}}
                        active={{option: {color: 'red'}}}>
                    <LayerEvent type="click" handler={this.handleClick}/>
                    <LayerEvent type="mousemove" handler={this.handleMouseMove}/>
                    </PointLayer>
                </AMapScene>
                <Card style={{ width: 270,position:"absolute",fontSize:"12px",opacity:'0.7'}}>
                    <p style={{"color":"#004A80"}}>将鼠标悬停在机场图标上获取机场信息</p>
                    <p>机场城市 |{currentAirPort.aptCcity}</p>
                    <p>机场名称 |{ currentAirPort.aptCname}</p>
                    <p style={{"color":currentAirPort.flightNumber>1000 ? '#B0120A':'black'}}>飞机数量 |{ currentAirPort.flightNumber}</p>
                </Card>
                <Drawer
                    title="航班信息"
                    placement="right"
                    closable={true}
                    size='large'
                    onClose={this.onClose}
                    visible={visibleDrawer}
                >
                <div style={{"width":"470px","height":"auto","position":"fixed","left":"10px","top":"10px","backgroundColor":"white","borderRadius":"6px"}}>
                  <Collapse defaultActiveKey={['1']} onChange={this.onChange}>
                  <Panel header="城市机场数量柱状图" key="1">
                  <Column{...aptColumnConfig} />
                  </Panel>
                  <Panel header="城市航班吞吐量堆叠柱状图" key="2">
                  <Column{...CityThroughputconfig} />
                  </Panel>
                  <Panel header="机型排名前十" key="3">
                  <Column{...flightColumnConfig} />
                  </Panel>
                  <Panel header="机场排名前十" key="4">
                  <Column{...aptTopColumnConfig} />
                  </Panel>
                  </Collapse>
                </div>
                <p>目的地-{currentAptCname}</p>
                <Table
                columns={columns}
                rowKey={record=>record.num}
                dataSource={ currentFlightData}
                pagination={ pagination}
                loading={ loading}
                onChange={this.handleTableChange}
              />
                </Drawer>
            </>
        )
    }
} 

export default FlightSystem;
